import frappe

def get_permission_query_conditions(user):

    if not user or user == "Administrator":
        return ""

    # 获取用户有权限的仓库列表
    warehouses = frappe.get_all(
        "User Permission",
        filters={
            "user": user,
            "allow": "Warehouse"
        },
        pluck="for_value"
    )

    # frappe.msgprint(f"当前用户: {user}")
    # frappe.logger().info(f"[HOOK] Triggered for user: {user}")
    # return """`tabSales Order`.name in ("SAL-ORD-2025-00002")"""
    if not warehouses:
        # 用户无仓库权限时，返回空结果
        return "0=1"  # 永远不成立的条件

    # 构建SQL条件：销售订单包含至少一个属于有权限仓库的物料
    return f"""
        EXISTS (
            SELECT 1 FROM `tabSales Order Item` soi
            WHERE soi.parent = `tabSales Order`.name
            AND soi.warehouse IN ({', '.join([f"'{wh}'" for wh in warehouses])})
        )
    """
